package com.pagoda.nerp.trade.common.extend;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by Jungle on 2016/12/15.
 */
public class AllRequestFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(AllRequestFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try{
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            logger.info("FILTER请求头信息:{}",httpServletRequest.getContentType());
            logger.info("FILTER请求地址:{}",httpServletRequest.getRequestURL());
            String contentType = httpServletRequest.getContentType();

            // 仅处理post 且 请求头为json的请求
            if(null != contentType && contentType.indexOf("application/json") != -1){

                // 防止流读取一次后就没有了, 所以需要将流继续写出去
                ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(httpServletRequest);
                try{
                    String body = HttpHelper.getBodyString(requestWrapper);
                    JSONObject jsonObject = JSONObject.parseObject(body);
                    logger.info("请求的body信息参数:{}", JSON.toJSONString(jsonObject,true));
                }catch(Exception e1){
                    logger.error("解析请求body参数为json异常!",e1);
                }
                chain.doFilter(requestWrapper,response);
                return;
            }
        }catch(Exception e){
            logger.error("初始获取请求body异常!",e);
        }
        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {
    }

    private String initJSONBody(HttpServletRequest httpServletRequest) {
        try {

        } catch (Exception e) {
            logger.info("请求的body不是JSON格式！", e);
        }
        return null;
    }
}
